<?php

$titlePage = __( 'Create your challenge' , 'sponsorpress');;

// Préparation du captcha
if($paramWpspoSetting['captcha']==1) {
    
    // Get a key from https://www.google.com/recaptcha/admin/create
    $publickey = $paramWpspoSetting['captchakeypu'];
    $privatekey = $paramWpspoSetting['captchakeypr'];
    # the response from reCAPTCHA
    $resp = null;
    # the error code from reCAPTCHA, if any
    $error = null;
    # was there a reCAPTCHA response?
    include_once(WP_PLUGIN_DIR . '/'.WPSPO_NAME_DIR.'/wpspo-includes/wpspo-recaptchalib.php');
}

// Modification du défi
if( isset($_GET['d']) && is_numeric($_GET['d']) && isset($_GET['leprojet']) && is_numeric($_GET['leprojet']) && $_GET['modifier']==1 && is_user_logged_in() ) {
    
    $verifUser = WPSPO_Defis::get_countByUserByProjet($_GET['d'], $current_user->ID, $_GET['leprojet']);
    //echo 'VERIFUSER:'.$_GET['d'].' - '.$current_user->ID.' -'.$verifUser;
        
    if($verifUser==1 ) {
        
        $titlePage = __( 'Modify this challenge' , 'sponsorpress');
        $optionsDefi = WPSPO_Defis::get_optionsById($_GET['d'], $current_user->ID);
        //print_r($optionsDefi);
        //echo 'VALUE'.$optionsDefi->defis_id.'->'.$current_user->ID;
        
        if( isset($optionsDefi->defis_id) ) {
            
            $getDefi = WPSPO_Defis::get($optionsDefi->defis_id_defi);
            //print_r($getDefi);
            if( !isset($getDefi->ID)) {
                exit('Impossible de lire le défi');
            }
            $idDefi = $getDefi->ID;
            $titleDefi = stripslashes(trim($getDefi->post_title));
            $textDefi = stripslashes(trim($getDefi->post_content));

            $idOptionsDefi = $optionsDefi->defis_id;
            
            $valueOptions = json_decode($optionsDefi->defis_option_value);
            //print_r($valueOptions);
            $dateDefi = $valueOptions->date_defis;
            $dateEndDefi = $valueOptions->date_end_defis;
            $villeDefi  = stripslashes(trim($valueOptions->ville_defis));
            $modeDefi  = $valueOptions->mode_defis;
            $modetextDefi  = stripslashes(trim($valueOptions->text_mode_defis));
            $coordDefis = $valueOptions->coord_defis;
            $recupLatLngDefi = explode("##", $coordDefis);
            $latDefis = $recupLatLngDefi[0];
            $lngDefis = $recupLatLngDefi[1];
            $typeDefis = $valueOptions->type_defis;
            $shareDefi = $valueOptions->share_defis;
            $sharePrive = $valueOptions->share_prive;
            $clePrive = $valueOptions->cle_defis;

            $modifierDefi = true;
            
        } else { 
            
            $url = add_query_arg('error', '1', get_permalink(WPSPO_ID_COMPTE));
            wp_safe_redirect($url);                    
            exit();
           
        }
        
    } else {
        //echo 'Erreur';
        echo wpspo_redirection(get_permalink(WPSPO_ID_COMPTE), "js");               
        exit();
        
    }
    
}

 /*
     * TRAITEMENT DU FORMULAIRE INSERT DEFI wpspo-form-defis.php
     */
    if (isset($_POST['submit-postdefi']) && isset($_POST['security-postdefi'])) {
    
        /*************************************************************************************************
		* On vérifie la validité du NONCE
		*************************************************************************************************/
        if (wp_verify_nonce($_POST['security-postdefi'], 'go-postdefi')) {
            
            if( trim($_POST['title_defis']) == '') {
                $erreur = 'title';
                $hasError = true;
            } else {
                $titleDefi = stripslashes(trim($_POST['title_defis']));
            }
            if( trim($_POST['text_defis']) == '') {
                $erreur = 'text';
                $hasError = true;
            } else {
                if(function_exists('stripslashes')) {
                    $textDefi = stripslashes(trim($_POST['text_defis']));
                } else {
                    $textDefi = trim($_POST['text_defis']);
                }
            }
            if( trim($_POST['date_defis']) == '') {
                $erreur = 'datestart';
                $hasError = true;
            } else {
                $dateDefi = trim($_POST['date_defis']);
            }
            $dateEndDefi = trim($_POST['date_end_defis']);
            if( trim($_POST['ville_defis']) == '') {
                $erreur = 'city';
                $hasError = true;
            } else {
                $villeDefi = trim($_POST['ville_defis']);
            }
            if($_POST['lat']) { $latDefis = $_POST['lat']; }
            if($_POST['lng']) { $lngDefis = $_POST['lng']; }
            if( trim($_POST['mode_defis']) == '') {
                $erreur = 'mode';
                $hasError = true;
            } else {
                $modeDefi = trim($_POST['mode_defis']);
            }
            if( trim($_POST['mode_defis']) == 1 && trim($_POST['text_mode_defis']=='')) {
                $erreur = 'modetext';
                $hasError = true;
            } else {
                $modetextDefi = trim($_POST['text_mode_defis']);
            }
            if( trim($_POST['certifie_defis']=='')) {
                $erreur = 'certifie';
                $hasError = true;
            } else {
                $condDefi = trim($_POST['certifie_defis']);
            }
            if($_POST['type_defis']) { $typeDefis = $_POST['type_defis']; }
            
            // Valeurs par défaut
            if($_POST['share_defis']=='') { $shareDefi = 0; } else { $shareDefi = $_POST['share_defis']; }
            if($_POST['share_prive']=='') { $sharePrive = 0; } else { $sharePrive = $_POST['share_prive']; }
            if($paramWpspoSetting['captcha']==1) {
                if ($_POST["recaptcha_response_field"]) {
                    $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
                    if ($resp->is_valid=='' or $resp->is_valid!=1) {
                        $erreur = 'code';
                        $hasError = true;
                    }
                } else {
                    $erreur = 'codempty';
                    $hasError = true;
                }
            }
                
            if(!isset($hasError)) {
            
                $titleDefi = stripslashes( trim( wp_strip_all_tags($_POST['title_defis']) ) );  
                if(function_exists('stripslashes')) {
                    $textDefi = stripslashes(trim($_POST['text_defis']));
                } else {
                    $textDefi = trim($_POST['text_defis']);
                }
                $dateDefi = trim( wp_strip_all_tags($_POST['date_defis']) );
                $dateEndDefi = trim( wp_strip_all_tags($_POST['date_end_defis']) );
                $villeDefi = trim( wp_strip_all_tags($_POST['ville_defis']) );
                $modeDefi = trim( wp_strip_all_tags($_POST['mode_defis']) );
                $modetextDefi = trim(wp_strip_all_tags($_POST['text_mode_defis']) );
                $condDefi = trim($_POST['certifie_defis']);
                if($_POST['lat']) { $latDefis = $_POST['lat']; }
                if($_POST['lng']) { $lngDefis = $_POST['lng']; }
                if($_POST['type_defis']) { $typeDefis = $_POST['type_defis']; }
                if($_POST['share_defis']=='') { $shareDefi = 0; } else { $shareDefi = $_POST['share_defis']; }
                if($_POST['share_prive']=='') { $sharePrive = 0; } else { $sharePrive = $_POST['share_prive']; }
                $clePrive = $_POST['cle_defis'];
                
                
                // On insère le PostType défis
                if( $_GET["modifier"] == 1 ) {
                    $insertPost =  WPSPO_Defis::update($_GET['d'], $textDefi, wp_strip_all_tags($titleDefi));
                } else {
                    // On insérer le post du défi
                    $insertPost =  WPSPO_Defis::save($current_user->ID, $textDefi, wp_strip_all_tags($titleDefi), $_POST["wpspo_choixprojets"]);
                }

                // Si l'insert à réussi on sauve les options 
                if(is_numeric($insertPost)) {
                    
                    // Génère une clé unique
                    if($sharePrive==1 && $clePrive=='') { $clePrive = strtoupper(uniqid()); } else { $clePrive = ''; }

                    // On construit les options
                    $array = array(
                        'date_defis' => $dateDefi,
                        'date_end_defis' => $dateEndDefi,
                        'ville_defis' => $villeDefi,
                        'mode_defis' => $modeDefi,
                        'text_mode_defis' => $modetextDefi,
                        'coord_defis' => $latDefis.'##'.$lngDefis,
                        'type_defis' => $typeDefis,
                        'share_defis' => $shareDefi,
                        'share_prive' => $sharePrive,
                        'cle_defis' => $clePrive
                    );
                    $dataJson = json_encode($array);

                    // On fixe à 0 l'envoi des notification des mails à l'admin du plugin
                    $envoiNotification = 0;

                    // On insère les options dnas la table perso
                    if( $_GET["modifier"] == 1 ) {
                        $insertOptions = WPSPO_Defis::updateOptions($_POST["wpspo_choixprojets"], $_GET['d'], $dataJson);
                        update_post_meta( $insertPost, 'wpspo_typedefi', $typeDefis, true );
                        $email_content = $paramWpspoEmailSetting['emailtextemodif'];
                        if($paramWpspoSetting['emaildefimodif']==1) { $envoiNotification = 1; }
                    } else {
                        $insertOptions = WPSPO_Defis::saveOptions($current_user->ID, $_POST["wpspo_choixprojets"], $insertPost, $dataJson);
                        add_post_meta( $insertPost, 'wpspo_typedefi', $typeDefis, true );
                        $email_content = $paramWpspoEmailSetting['emailtexte'];
                        if($paramWpspoSetting['emaildefi']==1) { $envoiNotification = 1; }
                    }

                    /* IMAGE UPLOAD */
                    if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
                    $uploadedfile = $_FILES['uploaded_file_defi'];
                    $upload_overrides = array( 'test_form' => false );
                    $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
                    if ( $movefile && $movefile['file']!='') {
                        $wp_filetype = $movefile['type'];
                        $filename = $movefile['file'];
                        $filetype = wp_check_filetype( basename( $filename ), null );
                        $wp_upload_dir = wp_upload_dir();
                        $attachment = array(
                            'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
                            'post_mime_type' => $wp_filetype,
                            'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
                            'post_content' => '',
                            'post_status' => 'inherit'
                        );
                        $errorImage = 'Le fichier est valide, et a été téléchargé avec succès ('.basename( $filename ).'). \ n';

                        // These files need to be included as dependencies when on the front end.
                        require_once( ABSPATH . 'wp-admin/includes/image.php' );
                        $attach_id = wp_insert_attachment( $attachment, $filename, $insertPost);
                        $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
                        wp_update_attachment_metadata( $attach_id, $attach_data );
                        //optional make it the featured image of the post it's attached to
                        $rows_affected = $wpdb->insert($wpdb->prefix.'postmeta', array('post_id' => $insertPost, 'meta_key' => '_thumbnail_id', 'meta_value' => $attach_id));
                    }
                
                    
                    // On envoi un email (si on a coché dans les params de  l'admin)
                    if($paramWpspoSetting['emaildefi']==1 or $paramWpspoSetting['emaildefimodif']==1) {

                        // traitement du contenu de l'email  
                        $args4 = array(
                            'ID'=>$insertPost, 
                            'PROJET' => get_page($_POST["wpspo_choixprojets"])->post_title,
                        );
                        $email_content4 = wpspo_content_traitement($email_content, $args4);
                        $tplHtml4 = str_replace('#TEXT#', $email_content4, $tplHtml);

                        $emailTo4 = sanitize_email($current_user->user_email);
                        $subject4 = __( 'Notice of' , 'sponsorpress').' '.get_bloginfo('name');
                        $headers4['From']    = "From: ".$paramWpspoSetting['emailresponse'];       
                        $headers4['Reply-To'] = "Reply-To: ".$paramWpspoSetting['emailplugin'];
                        if($envoiNotification==1) {
                            $headers4['Bcc'] = "Bcc: ".$paramWpspoSetting['emailplugin'];
                        }

                        add_filter('wp_mail_content_type',create_function('', 'return "text/html"; '));
                        if( !wp_mail( $emailTo4, $subject4, stripslashes($tplHtml4), $headers4 ) ) {
                            exit('Erreur envoi mail nouveau defi');
                        }
                        
                        if( $_GET["modifier"] == 1 ) {
                            $url = add_query_arg('insert', '1', get_permalink(WPSPO_ID_COMPTE).'#mesdefis' );
                            unset($_POST);
                        } else {
                            $url = add_query_arg('update', '1', get_permalink(WPSPO_ID_COMPTE).'#mesdefis' );
                            unset($_POST);
                        }
                        wp_safe_redirect($url);                    
                        exit();
                    } // envoi mail
                } // si insert reussi
            } // si verif champ ok
        } // si nonce OK
        
    }

?>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="<?php echo WP_CONTENT_URL; ?>/plugins/<?php echo WPSPO_NAME_DIR; ?>/wpspo-js/lib/jquery-1.4.4.min.js"></script>
<script src="<?php echo WP_CONTENT_URL; ?>/plugins/<?php echo WPSPO_NAME_DIR; ?>/wpspo-js/lib/jquery-ui-1.8.7.min.js"></script>
<script src="<?php echo WP_CONTENT_URL; ?>/plugins/<?php echo WPSPO_NAME_DIR; ?>/wpspo-js/jquery.ui.addresspicker.js"></script>
<script>
    $(function() {
        var addresspickerMap = $( "#ville_defis" ).addresspicker({
            regionBias: "fr",
      updateCallback: showCallback,
          elements: {
            map:      "#map",
            lat:      "#lat",
            lng:      "#lng",
            type:    '#type' 
          }
        });

        var gmarker = addresspickerMap.addresspicker( "marker");
        gmarker.setVisible(true);
        addresspickerMap.addresspicker( "updatePosition");

    $('#reverseGeocode').change(function(){ 
      $("#addresspicker_map").addresspicker("option", "reverseGeocode", ($(this).val() === 'true'));
    });

    function showCallback(geocodeResult, parsedGeocodeResult){
      $('#callback_result').text(JSON.stringify(parsedGeocodeResult, null, 4));
    }

    });
</script>

<div class="content" role="main">
    <a name="formdefis"></a>
    <?php
     if (isset($erreur)) {

        echo '<div class="wpspo-erreur">';

            switch ($erreur) {
                case 'title' :
                    _e("Please, enter challenge title", 'sponsorpress');
                    break;
                case 'text' :
                    _e("Please, enter challenge explanation", 'sponsorpress');
                    break;                
                case 'datestart' :
                    _e("Please, enter challenge date of start", 'sponsorpress');
                    break;                
                case 'city' :
                    _e("Please, enter challenge city", 'sponsorpress');
                    break;                
                case 'mode' :
                    _e("Please, enter challenge mode", 'sponsorpress');
                    break;                
                case 'modetext' :
                    _e("Please, enter the text mode challenge", 'sponsorpress');
                    break;                                
                case 'certifie' :
                    _e("Please, accept Terms for your challenge", 'sponsorpress');
                    break;                
                case 'code' :
                    _e("Please, enter the correct code", 'sponsorpress');
                    break;
                case 'codempty' :
                    _e("Oupss, you have not entered a code", 'sponsorpress');
                    break;
                default :
                    echo 'Une erreur est survenue.';

            }

        echo '</div>';

    }
    ?>
    
    <article <?php if( !empty( $rv['review'] ) ) echo $rv['review']; post_class('post-listing'); ?>>
            
        <div class="post-inner">
            
            <header class="entry-header">
                <h1 class="entry-title"><?php echo $titlePage; ?></h1>
            </header>

            <?php echo 'Vous souhaitez créer un défi sur le projet <strong><i>'.get_the_title($_GET['leprojet']).'</strong></i><br /><br />'; ?><div class="stripe-line"></div>
            <form method="post" name="add_defis" action="#formdefis" enctype="multipart/form-data">
                <ol class="wpspoforms">

                    <li>&nbsp;</li>
                 <li>
                    <label for="type_defis"><strong><?php _e('You are:', 'sponsorpress'); ?></strong></label>
                    <br /><select name="type_defis" id="type_defis" class="wpspo-select">
                        <?php
                            $listTypeDefi = wpspo_type_defi();
                            //print_r($listTypeDefi);
                            foreach ($listTypeDefi as $name => $nb) {
                                $addSelected = "";
                                if($typeDefis==$nb) { $addSelected = 'selected="selected"'; } 
                                echo '<option value="'.$nb.'" '.$addSelected.' >'.$name.'</option>
                                ';
                            }
                        ?>
                    </select>
                </li>

                <li>
                    <label for="title_defis"><strong><?php _e('Title of challenge', 'sponsorpress'); ?> (<?php _e('Required', 'sponsorpress'); ?>) :</strong></label>
                    <p style="font-size: 12px;margin-top:4px;"><i><?php _e('It will be used to present your challenge in various places on the site; therefore chosen an explicit title.', 'sponsorpress'); ?></i></p>
                    <input type="text" style="width: 80%;" name="title_defis" id="title_defis" value="<?php echo $titleDefi; ?>" style="font-size: 14px;" />
                </li>

                <li>
                    <label for="text_defis"><strong><?php _e('Description of challenge', 'sponsorpress'); ?> (<?php _e('Required', 'sponsorpress'); ?>) :</strong></label>
                    <br /><br /><textarea name="text_defis" id="text_defis" rows="5" cols="40" /><?php echo $textDefi; ?></textarea>
                </li>

                <li><label for="text_defis"><strong><?php _e('Picture for this challenge', 'sponsorpress'); ?> :</strong></label>
                    <?php if($errorImage != '') { ?>
                        <span class="error"><?php echo $errorImage; ?></span> 
                    <?php } ?>
                    <br />
                    <?php 
                    if($idDefi) {
                        echo '<p>'.__('This is your actually picture.', 'sponsorpress').'</p>';
                        $attachments = get_children(
                            array(
                            'post_parent' => $idDefi,
                            'post_type' => 'attachment',
                            'post_mime_type' => 'image',
                            'orderby' => 'menu_order',
                            'order' => 'DESC',
                            'numberposts' => 1
                            )
                        );
                        if( $attachments ) {
                            foreach( $attachments as $attachment ) :

                            echo wp_get_attachment_image($attachment->ID , 'thumbnail', '', array('class' => "wp-post-image")); 
                            endforeach;
                        }
                    }
                    ?>
                    <p><?php _e('To enhance your challenge, you can insert a picture.', 'sponsorpress'); ?></p>
                    <label for="upload_image"><input type="file" id="uploaded_file_defi" name="uploaded_file_defi" ></label>
  
                </li>

                <li>
                    <label for="date_defis"><strong><?php _e('Date of your challenge', 'sponsorpress'); ?></strong> <?php _e('(Required)', 'sponsorpress'); ?> :</label>
                    <br /><br /><?php _e('Start Date:', 'sponsorpress'); ?> <input type="text" size="9" class="DateDefi" name="date_defis" size="8" value="<?php echo $dateDefi; ?>"/>
                    <br /><?php _e('End Date:', 'sponsorpress'); ?> <input type="text" size="9" class="DateDefi" name="date_end_defis" size="8" value="<?php echo $dateEndDefi; ?>"/>
                </li>

                <li>

                    <label for="ville_defis"><strong><?php _e('City / Country', 'sponsorpress'); ?></strong> <?php _e('(Required)', 'sponsorpress'); ?> :</label>
                    <p style="font-size: 12px;margin-top:4px;"><i><?php _e('Start type in your city, then make your choice. You can move the marker to adjust workplace.', 'sponsorpress'); ?></i><p>
                    <input type="text" id="ville_defis" name="ville_defis" style="width: 80%;" value="<?php echo $villeDefi; ?>"/><br />
                    <?php //if( $villeDefi=='' ) { ?>
                    <div class='map-wrapper'>
                        <div id="map"></div>
                    </div>
                    <?php //} ?>
                    <input id="lat" name="lat"  type="hidden" value="<?php echo $latDefis; ?>">
                    <input id="lng" name="lng" type="hidden" value="<?php echo $lngDefis; ?>">
                </li>

                <li>
                    <hr style="border:2px solid #ccc;margin-top:15px;margin-bottom:15px;" /><label for="mode_defis"><strong><?php _e('Method of calculation donations', 'sponsorpress'); ?></strong> <?php _e('(Required)', 'sponsorpress'); ?> :</label>
                    <p style="font-size: 12px;margin-top:4px;"><i><?php _e('This is the way to calculate how much people should pay according to their pledge. This can be a fixed donation that is not based on your performance or else a gift based on a number of towers, miles or other things (in this case, write well in your explanation ).', 'sponsorpress'); ?></i><p>
                    <br /><br /><input type="radio" id="mode_defis" name="mode_defis" value="1" <?php if($modeDefi==1) { echo 'checked'; } ?> /> <?php echo get_wpspo_currency_symbol(); ?> / <input type="text" name="text_mode_defis" id="text_mode_defis" value="<?php echo $modetextDefi; ?>" /> (Ex : km, tour, etc...)

                    <br /><input type="radio" id="mode_defis" name="mode_defis" value="2" <?php if($modeDefi==2) { echo 'checked'; } ?> /> <?php _e('Fixed donation amount', 'sponsorpress'); ?><br /><br />

                </li>

                <li>
                    <hr /><input type="checkbox" id="share_defis" name="share_defis" value="1" <?php if($shareDefi==1) { echo 'checked'; } ?> /> <?php _e('Do you wish that others can subscribe to this challenge with you?', 'sponsorpress'); ?><br />
                    <p style="font-size: 12px;margin-top:4px;"><i><?php _e('This option allows you to choose between doing one or open challenge to everyone (unless the private mode is on)', 'sponsorpress'); ?></i></p><br />
                    <input type="checkbox" id="share_prive" name="share_prive" value="1" <?php if($sharePrive==1) { echo 'checked'; } ?> /> <?php _e('Do you want that your challenge is private?', 'sponsorpress'); ?><br />
                    <p style="font-size: 12px;margin-top:4px;"><i><?php _e('If the challenge is in private mode (for youth groups / Colonies, etc ...), a key will be provided for your guests can register and participate in your challenge. However, the challenge will be visible on the site.', 'sponsorpress'); ?></i></p>
                </li>

                <li>
                    <input type="checkbox" id="certifie_defis" name="certifie_defis" value="1" /> <?php _e('I certify that this challenge will person in danger, neither I nor anyone around me, and respects the law.', 'sponsorpress'); ?>
                </li>
                <?php if($paramWpspoSetting['captcha']==1) { ?>
                <li><br />
                      <script type="text/javascript">
                       var RecaptchaOptions = {
                           theme : 'clean',
                           lang : 'fr'
                            };
                    </script>
                    <?php echo recaptcha_get_html($publickey, $error); ?>
                </li>
                <?php } ?>

                <li class="buttons"><INPUT type="submit" name="submit-postdefi" style="display: inline-block;margin-top:10px;padding: 1.07em 3.5em;color: white;text-align:center;border-radius: 5px;text-shadow: none;background-color:#E15821;background: -webkit-linear-gradient(top,#E15821 0,#E15821 100%);text-decoration:none;border: 1px solid #E15821;" value="<?php _e('Send', 'sponsorpress'); ?>"></li>
                <?php if( $_GET["modifier"] == 1 ) { ?>
                        <input type="hidden" name="cle_defis" value="<?php echo $clePrive; ?>">
                        <input type="hidden" name="modify" value="1">
                <?php  } ?>
                <?php wp_nonce_field('go-postdefi','security-postdefi'); ?>
                <INPUT type="hidden" name="postedefis" value="true">
                <INPUT type="hidden" name="wpspo_choixprojets" value="<?php echo $_GET['leprojet']; ?>">
                </ol>
            </form>
            
        </div>
        
    </article>
    <div class="clear"></div>
</div>